from socket import socket, AF_INET, SOCK_DGRAM
from threading import Thread
from time import ctime
import msg_windom
import time

SHOW_NICK = "特朗普"
"""
发送消息流程
1. 数据准备
2. 发送数据
3. 消息提示
"""


def send(send_socket, ip, port):
    while True:
        time.sleep(0.2)
        if msg_windom.SEND_MESSAGE:
            # 程序版本号:数据包序列号:用户名:主机名:命令:消息内容
            send_data = "1:123456:" + SHOW_NICK + ":顶点:32:" + msg_windom.SEND_MESSAGE
            send_socket.sendto(send_data.encode("gbk"), (ip, port))
            msg_windom.SEND_MESSAGE = ""
            print("当前时间: ", ctime())
            print("消息已成功发送 ....")


"""
接收消息流程
1. 接收数据
2. 解析内容与指令(32:发送消息 33:回复 288:消息)
3. 构建响应数据,发送响应数据
4. 根据指令筛选消息来源和消息内容
"""


def recp(recp_socket):
    while True:
        recp_data = recp_socket.recvfrom(1024)
        # print("接收到的原始数据 recp_data: ", recp_data)

        recp_content = recp_data[0].decode("gbk")
        # print("接收到的消息是 recp_content: ", recp_content)

        recp_order = recp_content.split(":")[-2]

        if recp_order == "32":
            user = recp_content.split(":")[-4]
            recp_msg = recp_content.split(":")[-1]

            msg_windom.FRIEND_USER = user
            msg_windom.show_msg(recp_msg, False)

            print("\n当前时间: ", ctime())
            print("[消息来源]: ", user)
            print("[消息内容]: ", recp_msg)
            print()


# 买部电话
udp_socket = socket(AF_INET, SOCK_DGRAM)
# 插入电话卡
udp_socket.bind(("", 9999))
# 存入电话簿(ip确定网络主机,port确定应用程序)
remote_ip = input("请输入目的IP地址: ")
remote_port = int(input("请输入目的port地址: "))
# 开通电话业务
t1 = Thread(target=send, args=(udp_socket, remote_ip, remote_port))
t2 = Thread(target=recp, args=(udp_socket,))
t3 = Thread(target=msg_windom.window_show)

t1.start()
t2.start()
t3.start()
